<template>
  <div>
    <el-button type="primary">
      <el-icon :size="14">
        <search />
      </el-icon>
      查询
    </el-button>
  </div>
  <el-divider />
  <el-table :data="tasks.records" border style="width: 100%">
    <el-table-column prop="name" label="名称" width="380" />
    <el-table-column prop="created" label="创建时间" width="280" />
    <el-table-column label="状态" width="280">
      <template #default="scope">
        {{statuStr(scope.row.statu)}}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="danger" size="small" plain @click="showDstDialog(scope.row.id)">分配</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--分配绩效对话框-->
  <el-dialog v-model="dstDialog" title="绩效分配" width="50%" :close-on-click-modal="false">
    <el-table ref="tbBonus" :data="salaryItems" height="450" style="width: 100%"
              highlight-current-row
              :summary-method="getSummaries"
              show-summary>
      <el-table-column prop="id" label="编号" width="180" />
      <el-table-column prop="name" label="姓名" width="280" />
      <el-table-column label="绩效" prop="bonus">
        <template #default="scope">
          <el-input-number v-model="scope.row.bonus"
                           :min="0" :max="100000" :precision="2"
                           :controls="false"
                           v-show="scope.row.setting"
                           @blur="txtBlur(scope.row)" />
          <span v-show="!scope.row.setting">￥{{scope.row.bonus}}</span>
        </template>
      </el-table-column>
      <el-table-column>
        <template #header>
          <el-select size="small" @change="getSalaryItems" v-model="taskDepartId" placeholder="请选择部门">
            <el-option v-for="item in departs" :key="item.id" :label="item.departName" :value="item.id" />
          </el-select>
        </template>
        <template #default="scope">
          <el-button size="small" @click="changeRow(scope.row)" :disabled="scope.row.statu == 3">设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetBonus">重置</el-button>
        <el-button type="primary" @click="submitBonus">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, ref} from "vue";
import {
  finishDepartTask,
  getSalariesOfDepart,
  getTaskDeparts,
  getTasksOfStatu,
  setBouns,
  taskStatus
} from "@/api/wage";
import _ from "lodash";
import {ElMessage, ElMessageBox} from "element-plus";
import {Search} from "@element-plus/icons-vue";
  // 主组件实例
  const {proxy} = getCurrentInstance()

  // 任务列表
  const tasks = ref({
    current: 1,
    records: [],
    size: 10,
    pages: 0,
    total: 0
  })

  // 当前选中行
  const currentRow = ref(null)

  // 当前部门
  const currentDepart = ref(null)

  // 任务部门编号
  const taskDepartId = ref(null)

  // 绩效分配列表
  const salaryItems = ref([])
  const salaryItemsRaw = ref([])

  // 分配绩效对话框
  const dstDialog = ref(false)

  // 加载数据
  onMounted(() => {
    getTasks()
  })

  // 获取状态字符串
  const statuStr = (statu) => {
    return taskStatus[statu]
  }

  // 部门列表
  const departs = ref([])

  // 获取任务列表
  const getTasks = function () {
    getTasksOfStatu(1, 10, 2).then(res => {
      tasks.value = res.data
    })
  }

  // 获取部门人员列表
  const getSalaryItems = (departId) => {
    salaryItems.value = []
    currentDepart.value = _.find(departs.value, {'id': departId})
    getSalariesOfDepart(departId).then(res => {
      salaryItemsRaw.value = JSON.parse(JSON.stringify(res.data))
      salaryItems.value = res.data
    })
  }

  // 分配绩效
  const showDstDialog = (taskId) => {
    getTaskDeparts(taskId).then(res => {
      departs.value = res.data
    })
    dstDialog.value = true
  }

  // 重置数据
  const resetBonus = () => {
    salaryItems.value = JSON.parse(JSON.stringify(salaryItemsRaw.value))
  }

  // 上报分配方案
  const submitBonus = () => {
    // 如果没选中任务，直接返回
    if(!taskDepartId.value) return;

    let id = taskDepartId.value
    // 提醒
    ElMessageBox.confirm('提交后无法修改，确认？', '确认提交', {
      confirmButtonText: '提交',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      finishDepartTask(id).then(res => {
        getSalaryItems(id)  // 重新获取列表
        ElMessage.success("提交成功")
      })
    }).catch(() => {
      ElMessage.info('保存绩效取消')
    })
  }

  // 文本框失去焦点
  const txtBlur = (row) => {
    // 判断是否超额
    if(assignedBonus.value > Number(currentDepart.value.bonus)) {
      ElMessage.error('绩效分配超额了')
      return
    }
    // 保存绩效
    setBouns(row.id, row.bonus).then(res => {
      row.setting = false
    })
  }

  // 设置绩效金额
  const changeRow = (row) => {
    row.setting = !(row.setting | false)
    currentRow.value = row
  }

  // 已分配绩效总额
  const assignedBonus = computed(() => {
    const values = salaryItems.value.map((item, index) => {
      return item.bonus
    })
    let ex = 0
    if (!values.every((value) => Number.isNaN(value))) {
      ex = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    }
    return ex
  })

  // 计算总数
  const getSummaries = (param) => {
    const { columns, data } = param
    const sums = []
    let total = currentDepart.value? currentDepart.value.bonus : 'N/A'
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '总额：'
        return
      }
      else if(index === 1) {
        sums[index] = `￥${total}`
        return
      }
      else if(index === 2) {
        let ex = assignedBonus.value
        sums[index] = `￥ ${ex}`
        if(ex > total) {
          sums[3] = '超额了'
        }
      }
    })

    return sums
  }

  // 测试方法
  const test = () => {
    const bs = salaryItems.value.map((item, index) => {
      return item.bonus
    })
    console.log(bs)
  }
</script>

<style scoped>

</style>